package com.bustle.web.mbean.request;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import com.bustle.ejb.entity.User;
import com.bustle.ejb.service.AuthenticationException;
import com.bustle.ejb.service.AuthenticationManager;
import com.bustle.web.mbean.session.UserMBean;

@ManagedBean(name = "authentication")
@RequestScoped
public class AuthenticationMBean
{
  public String go()
  {
    return SCREEN;
  }

  public String connect()
  {
    try
    {
      User user = authenticationManager.authenticate(login, password);
      userMBean.setId(user.getId());
      userMBean.setFirstName(user.getFirstName());
      userMBean.setLastName(user.getLastName());
      return UserMBean.SCREEN;
    }
    catch (AuthenticationException anException)
    {
      anException.printStackTrace();
    }
    return null;
  }

  public String suscribe()
  {
    try
    {
      User user = authenticationManager.createUser(login, password);
      userMBean.setId(user.getId());
      return UserMBean.SCREEN;
    }
    catch (AuthenticationException anException)
    {
      anException.printStackTrace();
    }
    return null;
  }

  public String getLogin()
  {
    return login;
  }

  public void setLogin(String aLogin)
  {
    login = aLogin;
  }

  public String getPassword()
  {
    return password;
  }

  public void setPassword(String aPassword)
  {
    password = aPassword;
  }

  public void setUserMBean(UserMBean aUserMBean)
  {
    userMBean = aUserMBean;
  }

  protected String login;
  protected String password;

  @EJB
  protected AuthenticationManager authenticationManager;
  @ManagedProperty("#{user}")
  private UserMBean userMBean;

  static public final String SCREEN = "authentication.jsf";
}
